<?php
// $Id: template.php,v 3.2.1.13 2010/05/14 00:00:00 hass Exp $

/**
 * "Yet Another Multicolumn Layout" for Drupal
 *
 * (en) Central template for theme specific functions
 * (de) Zentrales Template für theme spezifische Funktionen
 *
 * @copyright       Copyright 2006-2010, Alexander Hass
 * @license         http://www.yaml-fuer-drupal.de/en/terms-of-use
 * @link            http://www.yaml-for-drupal.com
 * @package         yaml-for-drupal
 * @version         6.x-3.2.1.13
 * @lastmodified    2010-05-14
 */

/**
 * Include the central template.inc with global theme functions.
 */
include_once(realpath(dirname(__FILE__) .'/template.inc'));

/**
 * Alter some Drupal variables required by theme.
 */
function yaml_simple_preprocess_page(&$vars) {
  global $user;

  // Load the XML prolog for standard compliant browsers if caching is inactive.
  // The function page_set_cache() does not cache pages if $user->uid has a value.
  // Additional the XML prolog can only added to YAML for Drupal if a user is
  // logged into Drupal (caching inactive) or caching is globaly disabled on the site.
  if ((_yaml_browser_xml_prolog_compliant() && $user->uid) || (_yaml_browser_xml_prolog_compliant() && !(variable_get('cache', 0)))) {
    $vars['xml_prolog'] = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
  }

  // Add YAML Theme styles
  $vars['styles'] = _yaml_simple_add_styles($vars);

  // Dynamic sidebar switching.
  if ($vars['layout'] == 'none') {
    $vars['body_classes'] = $vars['body_classes'] .' hideboth';
  }
  elseif ($vars['layout'] == 'left') {
    $vars['body_classes'] = $vars['body_classes'] .' hidecol2';
  }
  elseif ($vars['layout'] == 'right') {
    $vars['body_classes'] = $vars['body_classes'] .' hidecol1';
  }

  // Customize footer code.
  $vars['footer_message'] = _yaml_preprocess_footer($vars['footer_message']);
}

/**
 * Alter some Drupal variables required by maintenance theme.
 */
function phptemplate_preprocess_maintenance_page(&$vars) {
  // Add YAML Theme styles.
  $vars['styles'] = _yaml_simple_add_styles($vars);

  // Disable empty sidebars.
  $vars['body_classes'] = $vars['body_classes'] .' hideboth';
}


function _yaml_simple_add_styles($vars = array()) {

  // Theme-Settings based on css/screen/basemod.css setting.
  $yaml_layout_page_width_min = '740px';
  $yaml_layout_page_width_max = '80em';

  $base_theme_directory = $vars['directory'];
  $styles = drupal_get_css($vars['css']);

  // The styles array is complete, get the styled css and append the
  // IE Hacks. Additional this allows to dynamically add packed or other iehacks.
  $styles .= "<!--[if lte IE 7]>\n";
  $styles .= '<style type="text/css" media="all">' . "\n";
  $styles .= '@import "'. base_path() . $base_theme_directory .'/yaml/core/iehacks'. (variable_get('preprocess_css', FALSE) ? '.pack' : '') .'.css";' . "\n";
  global $language;
  if (defined('LANGUAGE_RTL') && $language->direction == LANGUAGE_RTL) {
    $styles .= '@import "'. base_path() . $base_theme_directory .'/yaml/core/iehacks-rtl'. (variable_get('preprocess_css', FALSE) ? '.pack' : '') .'.css";' . "\n";
  }
  $styles .= '@import "'. base_path() . $base_theme_directory .'/css/patches/patch_3col_standard.css";' . "\n";
  $styles .= '@import "'. base_path() . $base_theme_directory .'/css/patches/patch_nav_vlist_drupal.css";' . "\n";
  $styles .= '@import "'. base_path() . $base_theme_directory .'/css/patches/patch_drupal.css";' . "\n";
  $styles .= "</style>\n";
  $styles .= "<![endif]-->\n";

  // IE 6 settings and styles.
  $styles .= "<!--[if lte IE 6]>\n";
  $styles .= '<style type="text/css" media="all">';
  $styles .= 'img, .pngtrans { behavior: url('. base_path() . $base_theme_directory .'/images/pngfix/iepngfix.htc) }';
  $styles .= '* html .page_margins { width: '. $yaml_layout_page_width_max .'; width: expression((document.documentElement && document.documentElement.clientHeight) ? ((document.documentElement.clientWidth < '. preg_replace('/[\D]+/', '', $yaml_layout_page_width_min) .') ? "'. $yaml_layout_page_width_min .'" : ((document.documentElement.clientWidth > (80 * 16 * (parseInt(this.parentNode.currentStyle.fontSize) / 100))) ? "'. $yaml_layout_page_width_max .'" : "auto" )) : ((document.body.clientWidth < '. preg_replace('/[\D]+/', '', $yaml_layout_page_width_min) .') ? "'. $yaml_layout_page_width_min .'" : ((document.body.clientWidth > (80 * 16 * (parseInt(this.parentNode.currentStyle.fontSize) / 100))) ? "'. $yaml_layout_page_width_max .'" : "auto" )));';
  $styles .= "</style>\n";
  $styles .= "<![endif]-->\n";

  // Return themed styles.
  return $styles;
}

function yaml_simple_theme() {
  return array(
    'links_secondary' => array(
      'arguments' => array(
        'links' => NULL,
        'attributes' => array('class' => 'links'),
        'settings' => array(
          'delimiter' => ' | ',
          'leftcab' => NULL,
          'rightcab' => NULL,
        )
      ),
      'template' => 'links-secondary',
    ),
  );
}

/**
 * Return a themed breadcrumb trail.
 *
 * @param $breadcrumb
 *   An array containing the breadcrumb links.
 * @return a string containing the breadcrumb output.
 */
function phptemplate_breadcrumb($node) {
	$trail = look_for_active_trail(menu_tree_page_data('primary-links'),true);
	  
	if(empty($trail)) {
		$trail = look_for_active_trail(menu_tree_page_data('menu-menu-right'));
	}
	$breadcrumb = array();

	foreach($trail as $el) {
		$breadcrumb[] = l($el['title'], $el['href'], $el['localized_options']);
	}

	if (!empty($breadcrumb)) {
		$last_breadcrumb_entry = count($trail)-1;
		if(strcmp($trail[$last_breadcrumb_entry]['title'],drupal_get_title())==0){
			array_pop($breadcrumb);
		}
		drupal_set_breadcrumb($breadcrumb);
		return implode(' > ', $breadcrumb) .' > '.drupal_get_title().'';
	}else{
		return "";
	}

}



/**
 * hook_theme()
 */
function parvis_v2_theme($existing, $type, $theme, $path) {  

  $theme = array();
  
  if(function_exists('_jquery_slideshow_get_presets')){
    foreach (_jquery_slideshow_get_presets() as $preset) {
      $theme['jquery_slideshow_formatter_jqs__'. $preset] = array(
        'arguments' => array('element' => NULL),
        'function'  => 'parvis_v2_jquery_slideshow_formatter'
      );
    }   
  }
 
  return $theme;
}

function parvis_v2_preprocess_page(&$vars, $hook) {
  if(drupal_is_front_page()) {
	$langs = array();
	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
		// break up string into pieces (languages and q factors)
		preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i',

		$_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

		if (count($lang_parse[1])) {
			// create a list like "en" => 0.8
			$langs = array_combine($lang_parse[1], $lang_parse[4]);

			// set default to 1 for any without q factor
			foreach ($langs as $lang => $val) {

			if ($val === '') $langs[$lang] = 1;

			}
			// sort list based on value
			arsort($langs, SORT_NUMERIC);
		}
	}
	//extract most important (first)
	foreach ($langs as $lang => $val) { break; }
	
	//if complex language simplify it
	if (stristr($lang,"-")) {$tmp = explode("-",$lang); $lang = $tmp[0]; }
	
	if($lang == "de" && i18n_get_lang() != "de"  && !isset($_COOKIE['visited'])){
		setcookie("visited", "yes", time() + 3600);
		drupal_goto($GLOBALS['base_url']."/de");
	}
  }
}


/**
 * process the good breadcrumb
 **/
function look_for_active_trail($tree,$primary = false) {
  $trail = array();
  while ($tree) {
    // Loop through the current level's items until we find one that is in trail.
    while ($item = array_shift($tree)) {
      if ($item['link']['in_active_trail']) {
        if(!$primary) $trail[] = $item['link'];
        $tree = empty($item['below']) ? array() : $item['below'];
        break;
      }
      $primary = false;
    }
    $primary = false;
  }
  return $trail;
}

function get_term_link($node) {
    //get the first term
	$terms = array();
    foreach($node->taxonomy as $tid => $taxonomie){
		$terms[] = l($taxonomie->name, 'taxonomy/term/'.$taxonomie->tid);
    }
	return implode(', ', $terms);
}


function get_link_back($node) {
    //get the first term
	$term = "";
	//echo "|".$_SERVER['QUERY_STRING']."|";
	if(strpos($_SERVER['QUERY_STRING'],'panier') !== false || 
				strpos($_SERVER['QUERY_STRING'],'warenkorb') !== false || 
				strpos($_SERVER['QUERY_STRING'],'login') !== false ||
				strpos($_SERVER['QUERY_STRING'],'abonnieren') !== false || 
				strpos($_SERVER['QUERY_STRING'],'abonnement') !== false || 
				strpos($_SERVER['QUERY_STRING'], 'librairie') !== false || 
				strpos($_SERVER['QUERY_STRING'],'buchhandlung') !== false){
		if(!empty($node) && sizeof($node->taxonomy)>0){
			return  l(t('Retour à la page précédente').', '.$term->name, 'taxonomy/term/'.$term->tid,array('attributes' => array('class' =>'link-back')));
		}else {
			/*foreach($node->taxonomy as $tid => $taxonomie){
			  if(sizeof($taxonomie==0)){
				break;
			  }
			  if($taxonomie->vid == 1){
				continue;
			  }
			  if(($node->type == 'article_sm' || $node->type == 'article_mh') && 
				($taxonomie->vid == 8 || $taxonomie->vid == 5)){
				$term = $taxonomie;
				break;
			  }
			  $term = $taxonomie;
			}*/
			$trail = look_for_active_trail(menu_tree_page_data('primary-links'),true);
		  
			if(empty($trail)) {
				$trail = look_for_active_trail(menu_tree_page_data('menu-menu-right'));
			} 
			$breadcrumb = array();

			foreach($trail as $el) {
				$breadcrumb[] = l(t('Retour à la page précédente').', '.$el['title'], $el['href'],array('attributes' => array('class' =>'link-back')));
			}
			if(sizeof($breadcrum)>1){
				return  $breadcrumb[sizeof($breadcrumb)-1];
			}else{
				return l(t('Retour à la page précédente'), "<front>",array('attributes' => array('class' =>'link-back')));
			}
			
		}
	}		
}

/**
 * theme_tagadelic_weighted() overriding
 * @param unknown_type $terms
 */
function parvis_v2_tagadelic_weighted($terms) {
  $output = '<ul class="nuage">';
  //traduce the taxonomy
  $terms = i18ntaxonomy_localize_terms($terms, array('name', 'description'));
  foreach ($terms as $term) {
    $output.= '<li>';
    $output .= l($term->name, taxonomy_term_path($term), array('attributes' => array('class' => "tagadelic level$term->weight", 'rel' => 'tag'))) ." \n";
    $output.= '</li>';
  }
  $output .= '</ul>';
  return $output;
}

/**
 * Base implementation of theme_jquery_slideshow
 *
 * @param array $element node element/field to style
 * @author Lee Rowlands <leerowlands at rowlands-bcs dot com>
 */
function parvis_v2_jquery_slideshow_formatter($element) {
    static $rendered;
    if (!$rendered) {
        $rendered = TRUE;
        $formatter = $element['#formatter'];
        $field_name = $element['#field_name'];
        $item = $element['#item'];
        $formatter = $element['#formatter'];
        $nid = $element['#item']['nid'];
        $node = node_load($element['#item']['nid']);;
        $jq_slideshow_id = 'jq-slideshow-'. $nid .'-'. $field_name;
        $output = '<div class="jquery_slideshow" id="'. $jq_slideshow_id .'">';
        $dets = explode('__', $formatter);
        $preset = $dets[1];
        if(is_array($node->{$field_name})){
          foreach ($node->{$field_name} as $image) {
            $output .= theme('imagecache', $preset, $image['filepath'], $image['data']['alt'], $image['data']['title']);       
          }
          $output .= '</div>';
         
          parvis_v2_jquery_slideshow_get_settings($jq_slideshow_id, $preset);
          return $output;
        }
    }
   
}


/**
 *Gets javascript settings for slideshow and sets up Drupal behaviour
 *
 *@param string $jq_slideshow_id dom id of slideshow
 *@param string $preset imagecache preset name
 *
 */
function parvis_v2_jquery_slideshow_get_settings($jq_slideshow_id, $preset) {
  //jquery_plugin_add('cycle');
  $data = _jquery_slideshow_get_actions($preset);

  $script = "Drupal.behaviors.jquerySlideshow = function(){
        $('.jquery_slideshow').css({height:'350px'});
        $('.jquery_slideshow').css({width:'600px'});
        $('#". $jq_slideshow_id ."').cycle({
          fx: '". variable_get('jquery_slideshow_effect', 'fade') ."',
          speed: ". variable_get('jquery_slideshow_speed', 500) .",
          timeout: ". variable_get('jquery_slideshow_timeout', 4000) .",
          next:   '#next',
          prev:   '#prev',
          after:   onAfter
        });
      };";

  $script .= "function onAfter(curr, next, opts) {
                 //get the current img
               $('#slideshow img').each(function(){
                   if( $(this).is(':visible') ) {
                        $('.slideshowinfo').remove();
                      if($(this).attr('title') || $(this).attr('alt')){
                        $(this).parent().parent().append('<div class=\"slideshowinfo\"><h2>'+$(this).attr('alt')+'</h2><p>'+$(this).attr('title')+'</p>');
                        $('.slideshowinfo').fadeIn(500);
}
                      }
               });
    }";

  drupal_add_js($script, 'inline');

}


function parvis_v2_preprocess_search_result(&$variables) {
  // Add node object to result, so we can display imagefield images in results.
  //echo "coco";
  //print_r($variables);
  //$nid = $result['node']->getField('nid');
  //$node = node_load($nid['value']);
  
  $url = $variables['url'];
  $nid = drupal_get_normal_path(substr($url,24));
  $nid = explode("/",$nid);
  $nid = $nid[sizeof($nid)-1];

  $n = node_load($nid);
  $n && ($variables['node'] = $n);
}


function phptemplate_preprocess_page(&$vars) {
  $vars['tabs2'] = menu_secondary_local_tasks();

  // Hook into color.module
  if (module_exists('color')) {
    _color_page_alter($vars);
  }
}

function phptemplate_menu_local_tasks() {
  return menu_primary_local_tasks();
}
